package com.by.basicgateway.security;

import com.by.toolkit.enums.ErrorCodeEnum;
import com.by.toolkit.model.Resp;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.by.toolkit.utils.ExceptionUtil.getStackTrace;

/**
 * 访问服务接口的用户权限不够时会调用
 *
 * @author Tian Wei
 * @version 1.0
 * @date 2023/12/21 5:14 PM
 */

@Slf4j
@Component
public class UserAccessDeniedHandler implements ServerAccessDeniedHandler, ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        return writeError(exchange);
    }

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
        return writeError(exchange);
    }

    private Mono<Void> writeError(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Resp resp = Resp.builder()
                .code(ErrorCodeEnum.PATH_NOT_AUTHORIZATION.getErrorCode())
                .msg(ErrorCodeEnum.PATH_NOT_AUTHORIZATION.getErrorMessage())
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            DataBuffer dataBuffer = response
                    .bufferFactory()
                    .wrap(objectMapper.writeValueAsBytes(resp));
            return response.writeWith(Mono.just(dataBuffer));
        } catch (Exception e) {
            log.warn("[UserAccessDeniedHandler][writeError] hasException:[{}] ", getStackTrace(e));
            return Mono.error(e);
        }
    }

}
